/*
 * @Author: 若城
 * @LastEditors: Please set LastEditors
 * @Description:
 * @FilePath: \type-h5\src\app.tsx
 * living Hell
 */
import React, { Component, useEffect, useState } from "react";
import { AtToast } from "taro-ui";
import "babel-polyfill";
import { observer, Provider } from "mobx-react";
import "taro-ui/dist/style/index.scss";
import stores from "./store/index";
import "./app.scss";
import { fetchinvitation, fetchPartner } from "./api";
import { getStore } from "./utils";
import { getCurrentInstance } from "@tarojs/taro";
// import VConsole from "vconsole";

// let vConsole = new VConsole();
const App = ({ children }: { children: React.ReactNode }) => {
  const { rootStore } = stores;
  const { router } = getCurrentInstance();
  const { setValues, getToken, setRouterChange, routerChange } = rootStore;

  useState(() => {
    const hash = window.location.hash;
    if (
      hash.indexOf("project-share") > -1 ||
      hash.indexOf("check-share") > -1 ||
      hash.indexOf("file-share") > -1
    ) {
      // 打开邀请链接，清空数据
      localStorage.clear();
      sessionStorage.clear();
    }
    const token = getStore("token");
    if (!token) {
      /** 获取匿名token */
      (window as any).tokenPromise = getToken();
    }
    return "";
  });
  useEffect(() => {
    if (
      !/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
        navigator.userAgent
      )
    ) {
      //TODO
      location.href = "https://web.mingque.com";
      return;
    }
    // 解决ios软键盘弹起收起的bug
    var u = navigator.userAgent;
    var flag;
    var myFunction;
    var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
    if (isIOS) {
      document.body.addEventListener("focusin", () => {
        //软键盘弹起事件
        flag = true;
        clearTimeout(myFunction);
      });
      document.body.addEventListener("focusout", () => {
        //软键盘关闭事件
        flag = false;
        if (!flag) {
          myFunction = setTimeout(function () {
            window.scrollTo({ top: 0, left: 0, behavior: "smooth" }); //重点  =======当键盘收起的时候让页面回到原始位置(这里的top可以根据你们个人的需求改变，并不一定要回到页面顶部)
          }, 200);
        } else {
          return;
        }
      });
    } else {
      return;
    }
    // document.body.addEventListener(
    //   "touchmove",
    //   function (e) {
    //     console.log(e);
    //     if (e._isScroller) return;
    //     e.preventDefault(); //阻止默认的处理方式(阻止下拉滑动的效果)
    //   },
    //   { passive: false }
    // ); //passive 参数不能省略，用来兼容ios和android

    // init();
  }, []);
  useEffect(() => {
    setRouterChange();
    window.scrollTo(0, 0);
  }, [router]);
  // taro无法返回空
  // return ''
  return <Provider {...stores}>{children}</Provider>;
};

export default observer(App);
